package service

import (
	"github.com/astaxie/beego/orm"
	"time"
	"howie_api/utils"
	"errors"
	"strconv"
	"fmt"
	"howie_api/models"
)

//登录用户
func UserLogin(user *models.UserData) (data *models.User, err error) {
	o := orm.NewOrm()
	data = &models.User{Account: user.Account}
	var token string
	if err = o.Read(data, "account"); err != nil {
		err = errors.New("用户名不存在")
		return
	}
	if data.Password != utils.MD5ToString(user.Password) {
		err = errors.New("密码错误")
		return
	}
	if data.AvailableTime <= time.Now().Unix() {
		err = errors.New("用户已经过期")
		return
	}
	token, err = utils.CreateToken(strconv.Itoa(data.Id))
	if err != nil {
		err = errors.New("创建用户会话信息失败")
		return
	}
	data.Token = token
	data.UpdateTime = time.Now().Unix()
	o.Update(data, "update_time")
	return

}

//注册用户
func RegisteredUsers(data *models.UserData) (user models.User, err error) {
	o := orm.NewOrm()
	user.Id = data.CreateId
	if err = o.Read(&user, ); err != nil {
		err = errors.New("未查询到该渠道")
		return
	}
	if user.Level > 2 {
		err = errors.New("该渠道权限不够")
		return
	}
	user = models.User{}
	user.Level = 3
	user.Account = data.Account
	var id int64
	if !models.WhetherTheUserExists(&user) {
		user.Password = utils.MD5ToString(data.Password)
		user.RegisterTime = time.Now().Unix()
		user.UpdateTime = time.Now().Unix()
		user.AvailableTime = time.Now().Unix() + 3600
		user.Allowed = 1
		user.CreateUid=data.CreateId
		if id, err = o.Insert(&user); err != nil {
			err = errors.New("创建用户信息失败")
			return
		}
		user.Token, err = utils.CreateToken(fmt.Sprintf("%d", id))
		if err != nil {
			err = errors.New("创建用户会话信息失败")
			return
		}
		return
	} else {
		err = errors.New("用户名已经存在")
		return
	}

}

//修改用户密码
func ChangePass(user *models.UserData) (err error) {
	o := orm.NewOrm()
	data := &models.User{Id: user.Uid}
	if err = o.Read(data, "id"); err != nil {
		err = errors.New("用户名不存在")
		return
	}
	if data.Password != utils.MD5ToString(user.Password) {
		err = errors.New("旧密码错误")
		return
	}
	data.Password = utils.MD5ToString(user.NewPassword)
	if _, err = o.Update(data, "password"); err != nil {
		err = errors.New("修改密码失败")
		return
	}
	return
}

//获取管理员账户
func GetAdministerList() (err error, user []models.UserList) {
	o := orm.NewOrm()
	var num int64
	num, err = o.Raw("SELECT * FROM `user` WHERE `user`.`level`<=2 ORDER BY `user`.`level`").QueryRows(&user)
	if err != nil {
		fmt.Println(err)
		return
	}
	if num <= 0 {
		err = errors.New("未查询到渠道信息")
		return
	}
	return
}
